package io.practice;

import java.io.*;
import java.util.Scanner;

//复制普通文件
public class CopyFile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要复制的普通文件（绝对路径OR相对路径）：");
        String sourcePath = scanner.next();
        File sourceFile = new File(sourcePath);
        if(!sourceFile.exists()){
            System.out.println("你要复制的文件不存在，请确认路径是否正确！");
            return;
        }

        if(sourceFile.isDirectory()){
            System.out.println("你要复制的文件不是普通文件，请确认路径是否正确！");
            return;
        }

        System.out.println("请输入你要复制到的目标路径（绝对路径OR相对路径）：");
        String destPath = scanner.next();
        File destFile = new File(destPath);

        if(destFile.exists()){
            if(destFile.isDirectory()){
                System.out.println("目标路径已经存在，且是一个目录，请确认路径是否正确！");
                return;
            }

            if(destFile.isFile()){
                System.out.println("目标路径已存在，是否需要覆盖（Y/N）：");
                String choice = scanner.next();
                if(choice.toLowerCase().equals("n")){
                    System.out.println("停止复制！");
                    return;
                }
            }
        }

        copyFile(sourceFile, destFile);
        System.out.println("复制成功！");
    }

    public static void copyFile(File sourceFile, File destFile){
        try(InputStream is = new FileInputStream(sourceFile);
            OutputStream os = new FileOutputStream(destFile)){
            byte[] bytes = new byte[1024];
            int n;
            while(true){
                n = is.read(bytes);
                if(n == -1){
                    break;
                }
                os.write(bytes, 0, n);
            }
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
